<template>
  <div class="project-kanban" v-loading="loading">
    <!-- 工具栏 -->
    <div class="kanban-toolbar">
      <div class="toolbar-left">
        <h3 class="kanban-title">{{ $t('project.kanban') }}</h3>
        <el-tag type="info" size="small">
          {{ projects.length }} {{ $t('project.projects') }}
        </el-tag>
      </div>
      <div class="toolbar-right">
        <el-button 
          v-if="canManage"
          type="primary" 
          :icon="Plus"
          @click="showCreateDialog = true"
        >
          {{ $t('project.createProject') }}
        </el-button>
        <el-button :icon="Refresh" @click="fetchProjects">
          {{ $t('common.refresh') }}
        </el-button>
      </div>
    </div>

    <!-- 看板区域 -->
    <div class="kanban-board">
      <!-- 规划中 -->
      <div class="kanban-column">
        <div class="column-header planning">
          <div class="column-title">
            <el-icon><Clock /></el-icon>
            <span>{{ $t('project.status.planning') }}</span>
          </div>
          <el-badge :value="planningProjects.length" class="column-badge" />
        </div>
        <div class="column-content">
          <draggable
            v-model="planningProjects"
            group="projects"
            item-key="id"
            @change="(event: any) => handleDragChange(event, 'PLANNING')"
            class="project-list"
          >
            <template #item="{ element }">
              <ProjectCard
                :project="element"
                :can-manage="canManage"
                @edit="handleEditProject"
                @delete="handleDeleteProject"
                @view="handleViewProject"
              />
            </template>
          </draggable>
          <div v-if="planningProjects.length === 0" class="empty-column">
            <el-empty :description="$t('project.noPlanningProjects')" :image-size="80" />
          </div>
        </div>
      </div>

      <!-- 进行中 -->
      <div class="kanban-column">
        <div class="column-header active">
          <div class="column-title">
            <el-icon><VideoPlay /></el-icon>
            <span>{{ $t('project.status.active') }}</span>
          </div>
          <el-badge :value="activeProjects.length" class="column-badge" />
        </div>
        <div class="column-content">
          <draggable
            v-model="activeProjects"
            group="projects"
            item-key="id"
            @change="(event: any) => handleDragChange(event, 'ACTIVE')"
            class="project-list"
          >
            <template #item="{ element }">
              <ProjectCard
                :project="element"
                :can-manage="canManage"
                @edit="handleEditProject"
                @delete="handleDeleteProject"
                @view="handleViewProject"
              />
            </template>
          </draggable>
          <div v-if="activeProjects.length === 0" class="empty-column">
            <el-empty :description="$t('project.noActiveProjects')" :image-size="80" />
          </div>
        </div>
      </div>

      <!-- 已完成 -->
      <div class="kanban-column">
        <div class="column-header completed">
          <div class="column-title">
            <el-icon><CircleCheck /></el-icon>
            <span>{{ $t('project.status.completed') }}</span>
          </div>
          <el-badge :value="completedProjects.length" class="column-badge" />
        </div>
        <div class="column-content">
          <draggable
            v-model="completedProjects"
            group="projects"
            item-key="id"
            @change="(event: any) => handleDragChange(event, 'COMPLETED')"
            class="project-list"
          >
            <template #item="{ element }">
              <ProjectCard
                :project="element"
                :can-manage="canManage"
                @edit="handleEditProject"
                @delete="handleDeleteProject"
                @view="handleViewProject"
              />
            </template>
          </draggable>
          <div v-if="completedProjects.length === 0" class="empty-column">
            <el-empty :description="$t('project.noCompletedProjects')" :image-size="80" />
          </div>
        </div>
      </div>

      <!-- 已归档 -->
      <div class="kanban-column">
        <div class="column-header archived">
          <div class="column-title">
            <el-icon><Box /></el-icon>
            <span>{{ $t('project.status.archived') }}</span>
          </div>
          <el-badge :value="archivedProjects.length" class="column-badge" />
        </div>
        <div class="column-content">
          <draggable
            v-model="archivedProjects"
            group="projects"
            item-key="id"
            @change="(event: any) => handleDragChange(event, 'ARCHIVED')"
            class="project-list"
          >
            <template #item="{ element }">
              <ProjectCard
                :project="element"
                :can-manage="canManage"
                @edit="handleEditProject"
                @delete="handleDeleteProject"
                @view="handleViewProject"
              />
            </template>
          </draggable>
          <div v-if="archivedProjects.length === 0" class="empty-column">
            <el-empty :description="$t('project.noArchivedProjects')" :image-size="80" />
          </div>
        </div>
      </div>
    </div>

    <!-- 创建项目对话框 -->
    <CreateProjectDialog
      v-model="showCreateDialog"
      :team-id="teamId"
      @success="handleCreateSuccess"
    />

    <!-- 编辑项目对话框 -->
    <EditProjectDialog
      v-model="showEditDialog"
      :project="selectedProject"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  Clock,
  VideoPlay,
  CircleCheck,
  Box
} from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import { projectApi } from '@/api/project'
import type { Project } from '@/types/project'
import ProjectCard from './ProjectCard.vue'
import CreateProjectDialog from './CreateProjectDialog.vue'
import EditProjectDialog from './EditProjectDialog.vue'

// Props
interface Props {
  teamId: number
  canManage: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  projectUpdated: []
}>()

const { t } = useI18n()

// 响应式数据
const loading = ref(false)
const projects = ref<Project[]>([])
const showCreateDialog = ref(false)
const showEditDialog = ref(false)
const selectedProject = ref<Project | null>(null)

// 计算属性 - 按状态分组的项目
const planningProjects = computed({
  get: () => projects.value.filter(p => p.status === 'PLANNING'),
  set: (value) => updateProjectsByStatus('PLANNING', value)
})

const activeProjects = computed({
  get: () => projects.value.filter(p => p.status === 'ACTIVE'),
  set: (value) => updateProjectsByStatus('ACTIVE', value)
})

const completedProjects = computed({
  get: () => projects.value.filter(p => p.status === 'COMPLETED'),
  set: (value) => updateProjectsByStatus('COMPLETED', value)
})

const archivedProjects = computed({
  get: () => projects.value.filter(p => p.status === 'ARCHIVED'),
  set: (value) => updateProjectsByStatus('ARCHIVED', value)
})

// 方法
const fetchProjects = async () => {
  try {
    loading.value = true
    const response = await projectApi.getTeamProjects(props.teamId)

    if (response.code !== 200) {
      throw new Error(response.message || '获取项目列表失败')
    }

    projects.value = response.data || []

    // 如果没有项目数据，显示提示
    if (projects.value.length === 0) {
      ElMessage.info(t('project.noProjects'))
    }
  } catch (error: any) {
    console.error('获取项目列表失败:', error)
    ElMessage.error(error.message || t('project.fetchError'))
  } finally {
    loading.value = false
  }
}

const updateProjectsByStatus = (status: string, newProjects: Project[]) => {
  // 移除旧的该状态项目
  projects.value = projects.value.filter(p => p.status !== status)
  // 添加新的该状态项目
  projects.value.push(...newProjects)
}

const handleDragChange = async (event: any, targetStatus: string) => {
  if (event.added) {
    // 项目被拖拽到新列
    const project = event.added.element
    const newStatus = targetStatus

    if (project.status !== newStatus) {
      try {
        // 显示加载状态
        loading.value = true

        // 调用API更新状态
        const response = await projectApi.updateProjectStatus(project.id, newStatus)

        if (response.code !== 200) {
          throw new Error(response.message || '更新项目状态失败')
        }

        // API调用成功后，重新获取项目数据以确保状态同步
        await fetchProjects()

        ElMessage.success(t('project.statusUpdateSuccess'))
        emit('projectUpdated')
      } catch (error: any) {
        console.error('更新项目状态失败:', error)
        ElMessage.error(error.message || t('project.statusUpdateError'))
        // 出错时也重新获取数据，恢复正确状态
        await fetchProjects()
      } finally {
        loading.value = false
      }
    }
  }
}



const handleCreateSuccess = () => {
  showCreateDialog.value = false
  fetchProjects()
  emit('projectUpdated')
}

const handleEditProject = (project: Project) => {
  selectedProject.value = project
  showEditDialog.value = true
}

const handleEditSuccess = () => {
  showEditDialog.value = false
  selectedProject.value = null
  fetchProjects()
  emit('projectUpdated')
}

const handleDeleteProject = async (project: Project) => {
  try {
    await ElMessageBox.confirm(
      t('project.deleteConfirmMessage', { name: project.name }),
      t('project.deleteConfirmTitle'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      }
    )

    loading.value = true
    const response = await projectApi.deleteProject(project.id)

    if (response.code !== 200) {
      throw new Error(response.message || '删除项目失败')
    }

    ElMessage.success(t('project.deleteSuccess'))
    fetchProjects()
    emit('projectUpdated')
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除项目失败:', error)
      ElMessage.error(error.message || t('project.deleteError'))
    }
  } finally {
    loading.value = false
  }
}

const handleViewProject = (project: Project) => {
  // 这里可以跳转到项目详情页面或打开项目详情对话框
  console.log('查看项目:', project)
}

// 生命周期
onMounted(() => {
  fetchProjects()
})

// 监听teamId变化
watch(() => props.teamId, () => {
  if (props.teamId) {
    fetchProjects()
  }
})
</script>

<style scoped lang="scss">
.project-kanban {
  .kanban-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 16px 0;

    .toolbar-left {
      display: flex;
      align-items: center;
      gap: 12px;

      .kanban-title {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }

    .toolbar-right {
      display: flex;
      gap: 12px;
    }
  }

  .kanban-board {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24px;
    min-height: 600px;
    // {{ AURA-X: Add - 设置列独立高度，防止高列影响其他列. Approval: 寸止(ID:fix-kanban-layout). }}
    align-items: start;

    .kanban-column {
      background: var(--el-bg-color-page);
      border-radius: 8px;
      border: 1px solid var(--el-border-color-light);

      .column-header {
        padding: 16px;
        border-bottom: 1px solid var(--el-border-color-light);
        display: flex;
        justify-content: space-between;
        align-items: center;

        .column-title {
          display: flex;
          align-items: center;
          gap: 8px;
          font-weight: 600;
          font-size: 14px;
        }

        &.planning {
          .column-title {
            color: var(--el-color-warning);
          }
        }

        &.active {
          .column-title {
            color: var(--el-color-primary);
          }
        }

        &.completed {
          .column-title {
            color: var(--el-color-success);
          }
        }

        &.archived {
          .column-title {
            color: var(--el-text-color-secondary);
          }
        }
      }

      .column-content {
        padding: 16px;
        min-height: 500px;
        // {{ AURA-X: Add - 设置最大高度和滚动，防止单列过高影响布局. Approval: 寸止(ID:fix-kanban-layout). }}
        max-height: 70vh;
        overflow-y: auto;

        .project-list {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .empty-column {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 200px;
        }

        // {{ AURA-X: Add - 优化滚动条样式，提升视觉体验. Approval: 寸止(ID:fix-kanban-layout). }}
        &::-webkit-scrollbar {
          width: 6px;
        }

        &::-webkit-scrollbar-track {
          background: var(--el-fill-color-lighter);
          border-radius: 3px;
        }

        &::-webkit-scrollbar-thumb {
          background: var(--el-border-color-darker);
          border-radius: 3px;

          &:hover {
            background: var(--el-border-color-dark);
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .project-kanban {
    .kanban-board {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}

@media (max-width: 768px) {
  .project-kanban {
    .kanban-toolbar {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;

      .toolbar-left,
      .toolbar-right {
        justify-content: center;
      }
    }

    .kanban-board {
      grid-template-columns: 1fr;
      gap: 16px;
    }
  }
}
</style>
